package com.javaDemo.ti;

/**
 * @ClassName: Buyongjiajianchenchuxiangjia
 * @Auther: csy https://leetcode-cn.com/problems/bu-yong-jia-jian-cheng-chu-zuo-jia-fa-lcof/solution/jing-jian-yi-dong-ban-by-legendarygz-ec8d/
 * @Date: 2021/3/14 16:47
 * @Description:
 */
public class Buyongjiajianchenchuxiangjia {

    //7＆2可以看作7*（7+2）＝63
    public static int add(int a, int b) {
        while (b != 0) {
            int c = (a & b) << 1;//c只保存进位的1
            a ^= b;//c已经保存了进位1，两个同1就不能再加，所以异或可以将不进位的部分加起来
            b = c;//进位部分下次循环继续加给a
        }
        return a;
    }

    // 快速幂算法求n的m次方
    //存在等式n^m = n^(m1+m2+m3+.....+mk) = n^m1 * n^m2 * n^m3 * ...* n^mk， 且m1 + m2 + m3 +....+mk = m
    public static int power(int n, int m) {
        int temp = 1, base = n;
        while (m != 0) {
            if ((m & 1) == 1) { // 判断奇偶,
                temp = temp * base;
            }
            base = base * base;
            m >>= 1; // 舍弃尾部位
        }
        return temp;
    }

    public static void main(String[] args) {
        int a = 5;
        int b = 3;
        // System.out.println((3&5));
        // System.out.println((2&0));
        // System.out.println((3|3));
        // System.out.println((3>>1));
        //  System.out.println((3^=6));
        // System.out.println(4%6);      //2  4

        // System.out.println(13/10);
        // System.out.println(10/13);
        // System.out.println(13%10);
        // System.out.println(10%13); //百分号前小就前  后小就余数
        //
        // System.out.println(13&10);
        // System.out.println(10&13);
        System.out.println(12 & 0x1);

        System.out.println(11 & 0x1);

        System.out.println(-111 & 0x1);

        System.out.println(-222 & 0x1);
        // System.out.println(11&1);
        // System.out.println(10&1);
        // System.out.println(19&1);
        // System.out.println(19&2);
        // System.out.println(20&2);

        // System.out.println(add(5, 3));

        // System.out.println(a ^ b);

        // System.out.println("3的5次方 = " + power(a, b));

        // add(4,7);

    }

    /**
     * 二进制求和.
     *
     * @param a
     * @param b
     * @return
     */
    public int adds(int a, int b) {
        while (b != 0) {
            int plus = (a ^ b); // 求和（不计进位）. 相同位置0，相反位置1
            b = ((a & b) << 1); // 计算进位. 先保留同为1的位，都为1的位要向左进位，因此左移1位
            a = plus;
        }
        return a;
    }
}
